//
//  NewsViewController.m
//  PrayerTimes
//
//  Created by Igor Karpenko on 6/8/13.
//  Copyright (c) 2013 Igor Karpenko. All rights reserved.
//

#import "NewsViewController.h"
#import "JBTabBarController.h"
#import "NewsTableViewCell.h"
#import <SDWebImage/UIImageView+WebCache.h>

#define SCREEN_NAME @"TheMuathTrust"

@interface NewsViewController ()

@end

static NSString *newsReuseIdentifier = @"newsReuseIdentifier";

@implementation NewsViewController

-(id) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (!self) {
        return nil;
    }
	
	self.title = NSLocalizedString(@"News", nil);
	self.tabBarItem.image = [UIImage imageNamed:@"gnr_newsIcon"];
	self.tabBarItem.selectedImage = [UIImage imageNamed:@"gnr_newsIcon_active"];
	
	_twitterDateFormatter = [[NSDateFormatter alloc] init];
	[_twitterDateFormatter setDateFormat:@"E MMM d H:mm:ss zzzz yyyy"];
	
	_prayerDateFormatter = [[NSDateFormatter alloc] init];
	[_prayerDateFormatter setDateFormat:@"d MMM"];
	

	_twitterEngine = [[FHSTwitterEngine alloc] initWithConsumerKey:@"ZxMQwLilerwAUeY5hPivg"
														 andSecret:@"hwSXRRfjjRchu8XFQsBJLvPDyUqNVjHjsAiUhGK0rA"];
	[self.twitterEngine loadAccessToken];
	return self;
}


#pragma mark - Memory managment

-(void) dealloc {
	[_twitterDateFormatter release];
	[_prayerDateFormatter release];
	
	[_tweets release];
	[_titleLabel release];
	[_overlayImage release];
	[_tableView release];
	[_loginButton release];
	[_titleLabel release];
	[_titleLine release];
	[super dealloc];
}


#pragma mark - Interface methods

-(void) viewDidLoad {
	[super viewDidLoad];
	
	_overlayImage.image = [_overlayImage.image resizableImageWithCapInsets:UIEdgeInsetsMake(230.0f, 0.0f, 20.0f, 0.0f)];
	
	if (![_twitterEngine isAuthorized]) {
		_tableView.hidden = YES;
		_loginButton.hidden = NO;
	}
}


-(void) viewDidUnload {
	[self setOverlayImage:nil];
	[self setTableView:nil];
	[self setLoginButton:nil];
	[self setTitleLabel:nil];
	[self setTitleLine:nil];
	[super viewDidUnload];
}


-(void) viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	
	[self changeLanguage];
	
	if ([_twitterEngine isAuthorized]) {
		id result = [_twitterEngine getTimelineForUser:SCREEN_NAME isID:NO count:20];
		if ([result isKindOfClass:[NSError class]]) {
			
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
														   message:((NSError *)result).localizedDescription
														  delegate:nil
												 cancelButtonTitle:@"OK"
												 otherButtonTitles:nil];
			[alert show];
			return;
		}
		
		self.tweets = result;
		[_tableView reloadData];
	}
}


#pragma mark - Action methods

-(IBAction) loginButtonTapped:(id)sender {
	[self twitterLogin];
}


#pragma mark - Private methods

-(void) twitterLogin {
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    [self.twitterEngine showOAuthLoginControllerFromViewController:rootViewController withCompletion:^(BOOL success) {
		_tableView.hidden = NO;
		_loginButton.hidden = YES;
    }];
}


-(void) changeLanguage {
	_titleLabel.text = AMLocalizedString(@"news", nil);
}

	
#pragma mark - Delegated methods

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	NSDictionary *tweet = [_tweets objectAtIndex:indexPath.row];
	NSString *url = [NSString stringWithFormat:@"https://twitter.com/%@/status/%@", SCREEN_NAME, [tweet objectForKey:@"id_str"]];
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
}


#pragma mark - Data source methods

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return _tweets.count;
}


-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	if (indexPath.row == 0) {
		return 75.0f;
	}
	NSDictionary *tweet = [_tweets objectAtIndex:indexPath.row];
	
	CGSize textSize = [[tweet objectForKey:@"text"] sizeWithFont:[UIFont fontWithName:@"Verdana" size:14.0f]
											   constrainedToSize:CGSizeMake(240.0f, 1000.0f)];
	return MAX(textSize.height + 35.0f, 70.0f);
}


-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	
	if (indexPath.row == 0) {
		UITableViewCell *firstCell = [[[UITableViewCell alloc] init] autorelease];
		[firstCell addSubview:_titleLabel];
		[firstCell addSubview:_titleLine];
		
		return firstCell;
	}
	
	NewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:newsReuseIdentifier];
	if (!cell ) {
		cell = [[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:newsReuseIdentifier];
	}
	
	NSDictionary *tweet = [_tweets objectAtIndex:indexPath.row];
	NSDictionary *user = [tweet objectForKey:@"user"];
	cell.userNameLabel.text = [user objectForKey:@"screen_name"];
	NSDate *date = [_twitterDateFormatter dateFromString:[tweet objectForKey:@"created_at"]];
	cell.dateLabel.text = [_prayerDateFormatter stringFromDate:date];
	
	cell.tweetLabel.text = [tweet objectForKey:@"text"];
	[cell.iconImage setImageWithURL:[NSURL URLWithString:[user objectForKey:@"profile_image_url"]] placeholderImage:[UIImage imageNamed:@"nws_placeholder"]];

	return cell;
}


-(NSIndexPath *) tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	if (indexPath.row == 0) {
		return nil;
	}
	return indexPath;
}


@end
